#
# "@(#) $Id: MultiPushButton.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from Utils.kdeemul import *
#
# a push button that supports multiple states, each represented by a key
# each state has an inconset and a signal, plus an optional next state
# for automatic transitions - usually only useful for testing purposes since
# the state usually represents some other external condition
#
class MultiPushButton(KPushButton):
	def __init__(self,label,container):
		KPushButton.__init__(self,label,container)
		self.state = 0
		self.states = {}
		QObject.connect(self,SIGNAL('clicked()'),self.doClick)

	def addState(self,key,icon,signal,nextState = None,label = None):
		self.states[key] = {'icon':icon,'signal':signal,'nextState':nextState,'label':label}
		if len(self.states)==1:
			self.setState(key)

	def setState(self,key):
		if self.state!=key:
			self.state = key
			self.setIconSet(self.states[key]['icon'])
			text = self.states[key]['label']
			# XXX DSM this kills the iconset in KDE 3.3
			#if text:
			#	self.setText(text)
			self.emit(PYSIGNAL("setState"),(self,key,text))
	
	def doClick(self):
		state = self.states[self.state]
		signal = state['signal']
		nextState = state['nextState']
		if signal: self.emit(signal,(self,None))
		if nextState: self.setState(nextState)

#
# a sublass the implements multistate buttons displayed solely by their
# icons, without the rest of the button chrome
#
class PixmapMultiPushButton(MultiPushButton):
	def __init__(self,label,container):
		MultiPushButton.__init__(self,label,container)

	def setState(self,key):
		oldState = self.state
		MultiPushButton.setState(self,key)
		if self.state!=oldState:
			pixmap = self.iconSet().pixmap(QIconSet.Large,QIconSet.Normal)
			self.setFixedSize(pixmap.size())

	def doErase(self):
		p = QPainter()
		p.begin(self)
		if self.backgroundMode() == Qt.X11ParentRelative:
			self.erase(0,0,self.width(),self.height())
		elif self.parentWidget() and self.parentWidget().erasePixmap():
			p.drawTiledPixmap(0,0,self.width(),self.height(),self.parentWidget().erasePixmap(),self.x(),self.y())
		else:
			p.fillRect(0,0,self.width(),self.height(),self.colorGroup().brush(QColorGroup.Background))
		p.end()
		
	def paintEvent(self,e):
		self.doErase()
		pixmap = self.iconSet().pixmap(QIconSet.Large,QIconSet.Normal)
		srcSize = pixmap.size()
		dstSize = self.size()
		posX = (dstSize.width()-srcSize.width())/2
		posY = (dstSize.height()-srcSize.height())/2
		bitBlt(self,QPoint(posX,posY),pixmap,pixmap.rect(),Qt.CopyROP)
